package com.yxr.mobileplayer.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;


import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.yxr.mobileplayer.R;
import com.yxr.mobileplayer.entity.MediaItem;
import com.yxr.mobileplayer.listener.NativeVideoOnSeekBarChangeListener;
import com.yxr.mobileplayer.receiver.BatteryReceiver;
import com.yxr.mobileplayer.tools.LArrayList;
import com.yxr.mobileplayer.tools.LG;
import com.yxr.mobileplayer.tools.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class SystemVideoPlayerActivity extends Activity implements View.OnClickListener{

    private VideoView videoview;
    private LinearLayout llTop;
    private ImageView ivBattery;
    private TextView tvTime;
    private Button btnVoice;
    private SeekBar seekbarVoice;
    private Button btnSwitchPlayer;
    private LinearLayout llBottom;
    private TextView tvCurrentTime;
    private SeekBar seekbarVideo;
    private TextView tvDuration;
    private Button btnVideoExit;
    private Button btnVideoPre;
    private Button btnVideoStartPause;
    private Button btnVideoNext;
    private Button btnVideoSwitchScreen;
    private TextView  tvName;
    private RelativeLayout rl_loading;
    /**
     * 是否是网络资源
     */
    private boolean isNetUri = false;
    /**
     * 进度更新
     */
    private static final int PROGRESS = 1001;
    private Utils utils;
    private  BatteryReceiver batteryReceiver;
    private List<MediaItem> mediaItems;
    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_system_video_player);
        initially();
        player();//播放
        error();  //错误监听
        completion();//播放完成监听
        findViews(); //加载组件
        phoneBatter();//手机电池
        //设置控制面板
        //使用自定义 media_controller.xml
        //使用系统 videoview.setMediaController(new MediaController(this));
        setButtonState();
    }

    private void initially(){
        utils = new Utils();
        videoview =  findViewById(R.id.videoview);
        mediaItems = (List<MediaItem>) getIntent().getSerializableExtra("mediaItems");
        position = getIntent().getIntExtra("position",0);
        if(null == mediaItems || mediaItems.size() == 0)
            return;
        MediaItem mediaItem = mediaItems.get(position);
        videoview.setVideoPath(mediaItem.getData());
        tvName = findViewById( R.id.tv_name );
        tvName.setText(mediaItem.getName());

    }

    private void phoneBatter(){
        //注册监听电量广播
        IntentFilter intentFilter = new IntentFilter();
        //监听手机电池量改变
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        batteryReceiver = new BatteryReceiver(ivBattery);
        registerReceiver(batteryReceiver,intentFilter);
    }

    private void player(){
        videoview.setOnPreparedListener( mediaPlayer -> {
//            mediaPlayer.setLooping(true);//设置循环播放，播放完的回调方法将不会调用
            //1.得到视频的总时长和SeeKBar.setMax();
            int duration = videoview.getDuration();
            seekbarVideo.setMax(duration);
            //设置总时长
            tvDuration.setText(utils.stringForTime(duration));
            //2.发消息更新
            handler.sendEmptyMessage(PROGRESS);
            videoview.start();
        });
    }

    private void error(){
        videoview.setOnErrorListener((mediaPlayer, what, extra) -> {
            Toast.makeText(SystemVideoPlayerActivity.this, "播放出错了", Toast.LENGTH_SHORT).show();
            return true;
        });
    }

    private void completion(){
        videoview.setOnCompletionListener(mediaPlayer -> {
//            Toast.makeText(SystemVideoPlayerActivity.this, "播放完成", Toast.LENGTH_SHORT).show();
//            finish();
            setPlayNext();
        });
    }
    private void findViews() {

        llTop = findViewById( R.id.ll_top );

        ivBattery = findViewById( R.id.iv_battery );

        tvTime = findViewById( R.id.tv_time );

        btnVoice = findViewById( R.id.btn_voice );
        btnVoice.setOnClickListener( this );

        seekbarVoice = findViewById( R.id.seekbar_voice );

        btnSwitchPlayer = findViewById( R.id.btn_switch_player );
        btnSwitchPlayer.setOnClickListener( this );

        llBottom = findViewById( R.id.ll_bottom );
        tvCurrentTime = findViewById( R.id.tv_current_time );
        //播放进度条
        seekbarVideo = findViewById( R.id.seekbar_video );
        seekbarVideo.setOnSeekBarChangeListener(new NativeVideoOnSeekBarChangeListener(videoview));

        tvDuration = findViewById( R.id.tv_duration );

        btnVideoExit = findViewById( R.id.btn_video_exit );
        btnVideoExit.setOnClickListener( this );

        btnVideoPre = findViewById( R.id.btn_video_pre );
        btnVideoPre.setOnClickListener( this );

        btnVideoStartPause = findViewById( R.id.btn_video_start_pause );
        btnVideoStartPause.setOnClickListener( this );

        btnVideoNext = findViewById( R.id.btn_video_next );
        btnVideoNext.setOnClickListener( this );

        btnVideoSwitchScreen = findViewById( R.id.btn_video_switch_screen );
        btnVideoSwitchScreen.setOnClickListener( this );
    }


    @Override
    public void onClick(View v) {
        if ( v == btnVoice ) {
            // Handle clicks for btnVoice
        } else if ( v == btnSwitchPlayer ) {
            // Handle clicks for btnSwitchPlayer
        } else if ( v == btnVideoExit ) {
            // Handle clicks for btnVideoExit
        } else if ( v == btnVideoPre ) {
            // Handle clicks for btnVideoPre
            setPlayPre();
        } else if ( v == btnVideoStartPause ) {
            if(videoview.isPlaying()){
                //暂停
                videoview.pause();
                //按钮设置播放状态
                btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_play_selector);
            }else{
                //播放
                videoview.start();
                //按钮设置暂停状态
                btnVideoStartPause.setBackgroundResource(R.drawable.btn_video_pause_selector);
            }
        } else if ( v == btnVideoNext ) {
            // Handle clicks for btnVideoNext
            setPlayNext();
        } else if ( v == btnVideoSwitchScreen ) {
            // Handle clicks for btnVideoSwitchScreen
        }
    }

    private void setPlayPre() {
        if (mediaItems == null || mediaItems.size() == 0) return;
        //播放上一个
        position--;
        if (position >= 0) {
            MediaItem mediaItem = mediaItems.get(position);
            videoview.setVideoPath(mediaItem.getData());//设置播放地址-
            tvName.setText(mediaItem.getName());
            isNetUri = utils.isNetUri(mediaItem.getData());
            setButtonState();
//            rl_loading.setVisibility(View.VISIBLE);
        }

    }

    private void setPlayNext() {
        if (mediaItems != null && mediaItems.size() > 0) {
            //播放下一个
            position++;
            if (position >= mediaItems.size())   finish();
            MediaItem mediaItem = mediaItems.get(position);
            videoview.setVideoPath(mediaItem.getData());//设置播放地址-
            tvName.setText(mediaItem.getName());
            //判断是否是网络资源
            isNetUri = utils.isNetUri(mediaItem.getData());
            setButtonState();
            if (position == mediaItems.size() - 1) {
                Toast.makeText(SystemVideoPlayerActivity.this, "已经是最后一个视频了", Toast.LENGTH_SHORT).show();
            }
//            rl_loading.setVisibility(View.VISIBLE);
        }
    }

    private void setButtonState() {
        if (mediaItems == null || mediaItems.size() == 0)
            Toast.makeText(this, "没有播放地址", Toast.LENGTH_SHORT).show();

        if (position == 0) {//第一个视频
            btnVideoPre.setEnabled(false);
            btnVideoPre.setBackgroundResource(R.drawable.btn_pre_gray);
        } else if (position == mediaItems.size() - 1) {//最后一个视频
            btnVideoNext.setEnabled(false);
            btnVideoNext.setBackgroundResource(R.drawable.btn_next_gray);
        } else {
            btnVideoNext.setEnabled(true);
            btnVideoNext.setBackgroundResource(R.drawable.btn_video_next_selector);
            btnVideoPre.setEnabled(true);
            btnVideoPre.setBackgroundResource(R.drawable.btn_video_pre_selector);
        }
    }


    @SuppressLint("Handlerleak")
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case PROGRESS:
                    //得到当前的播放进度
                    int currentPosition = videoview.getCurrentPosition();
                    seekbarVideo.setProgress(currentPosition);
                    tvCurrentTime.setText(utils.stringForTime(currentPosition));
                    //更新系统时间
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                    tvTime.setText(format.format(new Date()));
                    //每一秒更新一次
                    removeMessages(PROGRESS);
                    sendEmptyMessageDelayed(PROGRESS, 1000);
                    break;
            }
        }
    };






    /**
     * 生命周期
     * 创建到显示的： onCreate --> onStart --> onResume
     * 销毁： onPause --> onStop --> onDestroy
     *横竖屏切换 ： onPause --> onStop --> onDestroy --> onCreate --> onStart --> onResume
     *
     */
//    @Override
//    protected void onStart() {
//        super.onStart();
//        LG.e("onStart---");
//    }
//
//    @Override
//    protected void onResume() {
//        super.onResume();
//        LG.e("onResume---");
//    }
//
//    @Override
//    protected void onRestart() {
//        super.onRestart();
//        LG.e("onRestart---");
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        LG.e("onPause---");
//    }
//
//    @Override
//    protected void onStop() {
//        super.onStop();
//        LG.e("onStop---");
//    }
//
    @Override
    protected void onDestroy() {
        //销毁电池对象
        if(batteryReceiver != null){
            unregisterReceiver(batteryReceiver);
            batteryReceiver = null;
        }
        //优先调用子类，再调用父类，否则容易出现空指针异常
        super.onDestroy();
    }

}
